from django import forms
from django.core import validators
from .models import User
class BaseForm(forms.Form):
    def get_errors(self):
        errors = self.errors.get_json_data()
        #{'username': [{'message': '请输入邮箱类型', 'code': 'invalid'}], 'telephone': [{'message': '请输入正确格式的手机号', 'code': 'invalid'}], '__all__': [{'message': '两次密码不一致', 'code': ''}]}
        new_errors = {}
        for key, message_dict in errors.items():
            messagew = []

            for message in message_dict:
                messagew.append(message['message'])
            new_errors[key] = messagew
        #{'username': ['请输入邮箱类型']}
        return new_errors


class MyForm(BaseForm):
    # email = forms.EmailField(error_messages={"invalid":"请输入正确的邮箱"})

    username = forms.CharField(validators=[validators.EmailValidator(message="请输入邮箱类型")])
    telephone = forms.CharField(validators=[validators.RegexValidator(r'^1[35789]\d{9}',message="请输入正确格式的手机号")])

class RegisterForm(BaseForm):
    username = forms.CharField(validators=[validators.EmailValidator(message="请输入邮箱类型")])
    telephone = forms.CharField(validators=[validators.RegexValidator(r'^1[35789]\d{9}',message="请输入正确格式的手机号")])
    pwd1 = forms.CharField(max_length=30,min_length=6)
    pwd2 = forms.CharField(max_length=30,min_length=6)



    def clean_telephone(self):
        telephone = self.cleaned_data.get('telephone')
        res = User.objects.filter(telephone=telephone).exists()
        if res:
            raise forms.ValidationError(message="%s 已经被注册" % telephone)
        return telephone





        # 来到了 clean() 方法 说明你之前的每一个字段都验证成功了
    def clean(self):
        cleaned_data = super().clean()
        pwd1 = self.cleaned_data.get('pwd1')
        pwd2 = self.cleaned_data.get('pwd2')
        if pwd1 != pwd2:
            raise forms.ValidationError(message="两次密码不一致")
        return cleaned_data
